package com.thinkgem.jeesite.modules.qy.utils;


import com.thinkgem.jeesite.common.sms.email.SendEmailUtil;
import com.thinkgem.jeesite.common.utils.EhCacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by JohnShen on 2016/12/2.
 * 发送验证码
 */
public class VuthCode {

    protected static Logger logger = LoggerFactory.getLogger(VuthCode.class);

    public static final int SEDN_MOBILE_CODE = 111; //发送手机验证码
    public static final int SEND_EAMIL_CODE  = 222;//发送邮件验证码
    public static final String RECIPIENT  = "recipient"; //收件人
    public static final String TYPE  = "type"; //发送方式
    private static final  String TITLE = "轻院直播平台";
    private static final int MAX_CODE = 999999;
    private static final int MIX_CODE = 100000;
    private static HttpSession session ;


    /**
     * 生成验证码
     * @return 验证码
     */
    public static String createCode (){
        return String.valueOf( (int)(VuthCode.MIX_CODE + Math.random() *
                (VuthCode.MAX_CODE - VuthCode.MIX_CODE + 1)));
    }

    /**
     * 发送验证码
     * @param map
     */
    public static String sendCode(Map map , HttpSession session){
        VuthCode.session = session;
        String result = "success";
        int type = (Integer) map.get(VuthCode.TYPE);
        switch (type){
            case  VuthCode.SEDN_MOBILE_CODE:
                  break;
            case  VuthCode.SEND_EAMIL_CODE:
                  result = VuthCode.sendCodeByEamil(map);
                  break;
            default:
                  result = "错误的类型";
                  break;
        }
        return result;
    }

    private static String sendCodeByEamil(Map map){
        String result = "success";
        try {
            if(map.containsKey(VuthCode.RECIPIENT)){
                String recipient = map.get(VuthCode.RECIPIENT).toString(); //收件人
                String code = VuthCode.createCode();
                String content  =""+code+"(十分钟内有效)" ;
                if(VerificationTools.vaideEamil(recipient)){
                        EhCacheUtils.put("VuthCode",recipient ,code);
                        SendEmailUtil.sendEmail(content ,VuthCode.TITLE ,recipient);
                        VuthCode.session.setAttribute("Vuthcode" ,code );
                }else {
                    logger.info("incorrect email");
                    result = "incorrect email";
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.info("sending email error");
        }
        return  result;
    }

    public static void main(String[] args) {
        Map<String ,Object> map = new HashMap<String, Object>();
        map.put(VuthCode.RECIPIENT ,"2942591313@qq.com");
        map.put(VuthCode.TYPE ,VuthCode.SEND_EAMIL_CODE);
        VuthCode.sendCode(map ,null);
     }


}
